<?php

declare (strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Model;

use Hyperf\Database\Model\SoftDeletes;
use Hyperf\Database\Query\Builder;

class Role extends Model
{
    use SoftDeletes;

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected ?string $table = 'role';
    public static $statusList = [1 => '启用', -1 => '禁用'];

    public function manager()
    {
        return $this->belongsTo(Manager::class, 'manager_id');
    }

    public function managers()
    {
        return $this->hasMany(Manager::class, 'role_id');
    }

    public function getStatusTextAttribute()
    {
        return static::$statusList[$this->status] ?? '禁用';
    }

    /**
     * 启用/禁用
     * @return $this
     */
    public function handle()
    {
        if ($this->status == 1) {
            $this->status = -1;
        } else {
            $this->status = 1;
        }
        return $this;
    }

    /**
     * 关键字搜索
     * @param $q
     * @param $keyword
     * @return Builder
     */
    public function scopeKeyword($q, $keyword)
    {
        /** @var Builder $q */
        return $q->where(function ($q) use ($keyword) {
            /** @var Builder $q */
            $q->where('name', 'like', '%' . $keyword . '%');
        });
    }

    /**
     * 接口返回
     * @return array
     */
    public function toApi()
    {
        return [
            'id' => $this->id,
            'name' => $this->name ?? '',
            'rights' => $this->rights ? explode(',',$this->rights) : []
        ];
    }
}